﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace DevHelp
{

    public class INIhelp
    {
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath);

        //ini文件名称
        private static string inifilename = "Config.ini";
        //获取ini文件路径
        private static string inifilepath = Directory.GetCurrentDirectory() + "\\" + inifilename;

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetValue(string key, string section = "CONFIG")
        {
            StringBuilder s = new StringBuilder(1024);
            GetPrivateProfileString(section, key, "", s, 1024, inifilepath);
            return s.ToString().Replace("&换行&", "\r\n").Replace("&换行&", "\n").Replace("&换行&", "\r");
        }

        /// <summary>
        /// 设置
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetValue(string key, string value, string section = "CONFIG")
        {
            try
            {
                WritePrivateProfileString(section, key, value.Replace("\r\n", "&换行&").Replace("\n", "&换行&").Replace("\r", "&换行&"), inifilepath);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }



        /// <summary>
        /// 删除配置文件
        /// </summary>
        public static void delete()
        {
            try
            {
                if (System.IO.File.Exists(inifilepath))
                {
                    System.IO.File.Delete(inifilepath);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
